package com.xoa.controller.attend;

import com.xoa.model.attend.*;
import com.xoa.model.users.Users;
import com.xoa.service.attend.AttendService;
import com.xoa.service.attend.wrapper.AttendSetWrappers;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.attend.AttendExt;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/attend")
@EnableScheduling
public class AttendController {
    @Autowired
    private AttendService attendService;

    /**
     * 签到签到接口 （移动端）
     */
    @RequestMapping(value = "/addAttend", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper addAttend(Attend attend, HttpServletRequest req) throws ParseException {
        return attendService.newAttend(attend, req);
    }

    /**
     * 考勤机实现考勤
     */
    @RequestMapping(value = "/addAttendance", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper addAttendance() throws ParseException {
        return attendService.addAttendance();
    }

    /**
     * 考勤机实现考勤  连接数据库
     */
    @RequestMapping(value = "/addAttendances", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper addAttendances() throws ParseException, SQLException {
        return attendService.addAttendances();
    }

    /**
     * 获取签到页面所需数据 - 考勤返回的信息（移动端）
     */
    @RequestMapping(value = "/seledAttend", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper seledAttend(String attendDate, HttpServletRequest req, Integer uid) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(req, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(req.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        String sqlType = "xoa" + loginDateSouse;
        if (uid == null) {
            Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
            uid = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(), redisSessionId).getUid();
        }
        if (StringUtils.checkNull(attendDate)) {
            attendDate = DateFormat.getDatestr(new Date());
        }
        return attendService.attendList(attendDate, uid, sqlType);
    }

    /**
     * 手机考勤排行榜（前十个用户）（移动端）
     */
    @RequestMapping(value = "/attendanceList", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper attendanceList(String date) {
        if (StringUtils.checkNull(date)) {
            date = DateFormat.getDatestr(new Date());
        }
        return attendService.mycheckList(date);
    }

    /**
     * 我的考勤统计-汇总 （移动端）
     */
    @RequestMapping(value = "/myAttendance")
    public BaseWrapper myAttendance( String strat , HttpServletRequest req) throws ParseException {
        return attendService.myAttend(strat, req);
    }

    /**
     * 公司考考勤（移动端）
     */
    @RequestMapping(value = "/companyAttendance")
    public BaseWrapper companyAttendance(String date) {
        return attendService.findListAll(date);
    }

    /**
     * 我的签到-个人考勤详情（移动端）
     */
    @RequestMapping(value = "/normalCondition")
    public BaseWrapper normalCondition(String year, String month, HttpServletRequest request) throws ParseException {
        return attendService.normalCondition(year, month, request);
    }

    /**
     * PC - 个人事务-个人考勤
     */
    @RequestMapping(value = "/personalAttendance", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper PersonalAttendance(String date, HttpServletRequest request) throws ParseException {
        return attendService.personalAttend(date, request);
    }

    /**
     * 创建人：季佳伟
     * 创建时间：2017-11-20  下午4:30:17
     * 方法介绍：查询当天登录人的考勤状况
     * 参数说明：
     */
    @RequestMapping(value = "/PersonalTodayAttendance", produces = {"application/json;charset=UTF-8"})
    public BaseWrapper PersonalTodayAttendance(String date, HttpServletRequest request) throws ParseException {
        return attendService.PersonalTodayAttendance(date, request);
    }

    @RequestMapping(value = "/AttendanceStatistics", produces = {"application/json;charset=UTF-8"})
    public AttendSetWrappers AttendanceStatistics(String beginDate, String endDate, HttpServletRequest req) throws ParseException {
        return attendService.AttendanceStatistics(beginDate, endDate, req);
    }

    @RequestMapping(value = "/pcAttendanceStatistics", produces = {"application/json;charset=UTF-8"})
    public AttendSetWrappers pcAttendanceStatistics(String beiginDate, String endDate, String deptId, String dutyType,
                                                    String deptName,
                                                    String uid, HttpServletRequest req) throws ParseException {
        return attendService.pcAttendanceStatistics(beiginDate, endDate, deptId, dutyType, uid, req);
    }

    @RequestMapping(value = "/selectAttendParticularss", produces = {"application/json;charset=UTF-8"})
    // /attend/selectAttendParticularss
    public ToJson selectAttendParticularss(String stratDate, String endDate, Integer uid) {
        return attendService.selectAttendParticulars(stratDate, endDate, uid);
    }


    @RequestMapping("/selectAttendDate")
    public ToJson selectAttendDate(Integer uid) {
        return attendService.selectAttendDate(uid);
    }


    /**
     * 考勤详情 侯王鑫
     *
     * @param request
     * @return 查询的部门信息
     */
    @RequestMapping("/queryAttendDept")
    public ToJson queryAttendDept(HttpServletRequest request) {
        return attendService.queryAttendDept(request);
    }


    /**
     * 考勤详情 侯王鑫
     *
     * @param request
     * @return 查询的用户信息
     */
    @RequestMapping("/queryAttendUsers")
    public ToJson queryAttendUsers(HttpServletRequest request) {
        return attendService.queryAttendUsers(request);
    }


    @RequestMapping("/findAttendList")
    public AttendSetWrappers findAttendByDept(String dutyType, Integer deptId,
                                              String startTime, String endTime, Integer pageNo, Integer pageSize, HttpServletRequest req) throws Exception {

        return attendService.findAttendList(dutyType, deptId, startTime, endTime, pageNo, pageSize, req);
    }


    @ResponseBody
    @RequestMapping("/reportAttend")
    public void reportDutyFormByUserId(HttpServletRequest request, HttpServletResponse response, String dutyType, Integer deptId,
                                       String startTime, String endTime, Integer pageNo, Integer pageSize, String[] secondTitles) throws Exception {//IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException ,
        HSSFWorkbook workbook2 = new HSSFWorkbook();
        workbook2.createSheet();
        Map<String, String> map = new HashMap<>();
        map.put("姓名", "userName");
        map.put("应出勤天数", "yingChuQin");
        map.put("实际出勤天数", "shiJiChuQin");
        map.put("全勤", "quanQin");
        map.put("上班准时", "zhengChangQianDao");
        map.put("下班准时", "zhengChangQianTui");
        map.put("迟到", "chiDao");
        map.put("早退", "zaoTui");
        map.put("未签到", "weiQianDao");
        map.put("未签退", "weiQianTui");
        map.put("旷工天数", "kuangGong");
        map.put("设备异常", "sheBeiYiChang");
        map.put("外勤", "waiQin");
        map.put("请假", "attendLeaveDate");
        map.put("外出加班", "attendOutDate");
        map.put("出差", "attendEvectionDate");
//        String[] secondTitles = {"姓名","应出勤天数","实际出勤天数","全勤","上班准时","下班准时",
//                "迟到","早退","未签到","未签退","旷工天数","设备异常","外勤","请假","外出加班","出差"};
        HSSFSheet sheet = workbook2.getSheetAt(0);
        HSSFRow rowField = sheet.createRow(0);
        String[] beanProperty = {};
        for (int i = 0; i < secondTitles.length; i++) {
            HSSFCell cell = rowField.createCell(i);
            cell.setCellValue(secondTitles[i]);

            beanProperty[i] = map.get(secondTitles[i]);
        }
//        String[] beanProperty = {"userName","yingChuQin","shiJiChuQin","quanQin","zhengChangQianDao","zhengChangQianTui","chiDao",
//                "zaoTui","weiQianDao","weiQianTui","kuangGong","sheBeiYiChang","waiQin","attendLeaveDate","attendOutDate","attendEvectionDate"};
        BaseWrapper attendList = attendService.findAttendList(dutyType, deptId, startTime, endTime, pageNo, pageSize, request);
        HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, (List<AttendExt>) attendList.getData(), beanProperty);
        ServletOutputStream out = response.getOutputStream();
        String filename = "考勤表.xls";
        filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        workbook.write(out);
        out.close();
    }

    @ResponseBody
    @RequestMapping("/importStaffInfo")
    public BaseWrapper importAttend(MultipartFile file, HttpServletRequest request) {
        return attendService.importAttend(file, request);
    }


    @ResponseBody
    @RequestMapping("/findAttendList2")
    public AttendSetWrappers testAttend(@RequestParam(value = "dutyType", required = false) Integer dutyType,
                                        @RequestParam(value = "deptId", required = false) Integer deptId,
                                        @RequestParam(value = "beginDate", required = false) String beginDate,
                                        @RequestParam(value = "endDate", required = false) String endDate,
                                        @RequestParam(value = "pageNo", required = false) Integer pageNo,
                                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                        @RequestParam(value = "uid", required = false) Integer uid,
                                        HttpServletRequest req, HttpServletResponse response,
                                        @RequestParam(value = "exType", required = false) String exType) {
        Map<String, Object> map = new HashMap();
        map.put("response", response);
        //导出类型
        map.put("exType", exType);
        return attendService.findAttendList3(dutyType, deptId, beginDate, endDate, pageNo, pageSize, uid, req, map);
    }

    /*
     * 创建作者： 于润鹏
     * 创建日期：  18.11.8 上午 11:20
     * 方法介绍：    考勤统计导出
     * 参数说明：  @param request
     * 参数说明:   @return
     *
     */
    @RequestMapping("/outAttend")
    @ResponseBody
    ToJson out(@RequestParam(value = "dutyType") Integer dutyType,
               @RequestParam(value = "deptId") Integer deptId,
               @RequestParam(value = "beginDate") String beginDate,
               @RequestParam(value = "endDate") String endDate,
               @RequestParam(value = "uid") Integer uid,
               HttpServletRequest req, HttpServletResponse response
    ) {
        //导出
        ToJson json = new ToJson();
        return json;
    }

    /**
     * 创建作者： 于润鹏
     * 创建日期：  18.11.8 上午 11:20
     * 方法介绍：    考勤统计导入
     * 参数说明：  @param request
     * 参数说明:   @return
     **/
    @ResponseBody
    @RequestMapping("/importAttend")
    public ToJson importStaffInfo(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        return attendService.importAttend(file, request, response, session);
    }


    @ResponseBody
    @RequestMapping("/exporAttendExcel")
    public ToJson outAttend2(
            @RequestParam(value = "dutyType", required = false) Integer dutyType,
            @RequestParam(value = "deptId", required = false) Integer deptId,
            @RequestParam(value = "beginDate", required = false) String beginDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "pageNo", required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "uid", required = false) Integer uid,
            HttpServletRequest req,
            HttpServletResponse response) {
        return attendService.exporAttendExcel(dutyType, deptId, beginDate, endDate, pageNo, pageSize, uid, req, response);
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：同步考勤数据
     * @创建时间：11:20 2019/4/19
     **/
    @RequestMapping("synAttend")
    @ResponseBody
    public ToJson synAttend(String beginDate, String endDate) {
        return attendService.synAttend(beginDate, endDate);
    }


    /***
     * 统计一天的请假次数 出勤次数 迟到次数 应出勤  加班
     * @param date
     * @return
     */
    @RequestMapping(value = "/findDateList")
    public BaseWrapper findDateList(String date) {
        return attendService.findListDateAll(date);
    }

    /**
     * 一周的请假，出勤，迟到 (次数，日期，天数)统计
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/queryDateAll")
    public BaseWrapper queryDateAll(String beginDate, String endDate) {
        return attendService.queryDateAll(beginDate, endDate);
    }
    //获取当前登录人本季度的请假，外出，加班情况
    @RequestMapping("queryCountDataByQuarter")
    @ResponseBody
    public ToJson queryCountDataByQuarter(HttpServletRequest request){
        return  attendService.queryCountDataByQuarter(request);
    }
    //获取当前登录人本月度的请假，外出，加班情况
    @RequestMapping("queryCountDataByMonth")
    @ResponseBody
    public ToJson queryCountDataByMonth(HttpServletRequest request){
        return  attendService.queryCountDataByMonth(request);
    }
    //获取当前登录人本年度的请假，外出，加班情况
    @RequestMapping("queryCountDataByYear")
    @ResponseBody
    public ToJson queryCountDataByYear(HttpServletRequest request){
        return  attendService.queryCountDataByYear(request);
    }

}


